/*
 * A JMX Adaptor using IIOP
 * Part of the GICOM project
 */
package jmx.iiop;

import gicom.generated.adminServices.MBeanServerException;
import gicom.generated.adminServices.MBeanServerOperations;
import gicom.generated.adminServices.MBeanServerPOA;

import java.lang.reflect.Constructor;
import java.util.Iterator;
import java.util.Set;

import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.BadAttributeValueExpException;
import javax.management.BadBinaryOpValueExpException;
import javax.management.BadStringOperationException;
import javax.management.DynamicMBean;
import javax.management.InvalidApplicationException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.RuntimeOperationsException;

import org.omg.CORBA.Any;

/**
 * A JMX Adaptor using IIOP
 * @author Didier Donsez
 *
 */
public class IIOPAdapter extends MBeanServerPOA implements MBeanServerOperations, DynamicMBean, javax.management.MBeanRegistration {

	// MBeanServerOperations methods
	
	public String[] queryNames(String objectName, String queryExp) throws MBeanServerException {
		if(mbeanServer==null) throw new MBeanServerException("not connected to the MBeanServer");
		Set<ObjectName> objectNames;
		try {
			objectNames = mbeanServer.queryNames(
					new ObjectName(objectName),
					new QueryExp(){ // TODO
						public boolean apply(ObjectName name)
								throws BadStringOperationException,
								BadBinaryOpValueExpException,
								BadAttributeValueExpException,
								InvalidApplicationException {
//							 TODO
							return true;
						}
		
						public void setMBeanServer(MBeanServer s) {
//							 TODO
						}
			});
		} catch (MalformedObjectNameException e) {
			throw new MBeanServerException(e.getMessage());
		} catch (NullPointerException e) {
			throw new MBeanServerException(e.getMessage());
		}
		String[] onames=new String[objectNames.size()];
		int i=0;
		for (Iterator iterator = objectNames.iterator(); iterator.hasNext();) {
			ObjectName name = (ObjectName) iterator.next();
			onames[i++]=name.getCanonicalName();
		}
		return onames;
	}

	/**
	 * Allows the value of the specified attribute of the Dynamic MBean to be
	 * obtained.
	 */
	public Object getAttribute(String attribute_name)
			throws AttributeNotFoundException, MBeanException,
			ReflectionException {

		// Check attribute_name is not null to avoid NullPointerException later
		// on
		if (attribute_name == null) {
			throw new RuntimeOperationsException(new IllegalArgumentException(
					"Attribute name cannot be null"),
					"Cannot invoke a getter of " + dClassName
							+ " with null attribute name");
		}

		// Check for a recognized attribute_name and call the corresponding
		// getter
		/*if (attribute_name.equals("Message")) {
			return getMessage();
		}
		*/
		
		// If attribute_name has not been recognized throw an
		// AttributeNotFoundException
		throw (new AttributeNotFoundException("Cannot find " + attribute_name
				+ " attribute in " + dClassName));
	}

	/**
	 * Sets the value of the specified attribute of the Dynamic MBean.
	 */
	public void setAttribute(Attribute attribute)
			throws AttributeNotFoundException, InvalidAttributeValueException,
			MBeanException, ReflectionException {

		// Check attribute is not null to avoid NullPointerException later on
		if (attribute == null) {
			throw new RuntimeOperationsException(new IllegalArgumentException(
					"Attribute cannot be null"), "Cannot invoke a setter of "
					+ dClassName + " with null attribute");
		}
		String name = attribute.getName();
		Object value = attribute.getValue();

		if (name == null) {
			throw new RuntimeOperationsException(new IllegalArgumentException(
					"Attribute name cannot be null"),
					"Cannot invoke the setter of " + dClassName
							+ " with null attribute name");
		}
		/*
		// Check for a recognized attribute name and call the corresponding
		// setter
		//
		if (name.equals("Language")) {
			// if null value, try and see if the setter returns any exception
			if (value == null) {
				try {
					setMessage(null);
				} catch (Exception e) {
					throw (new InvalidAttributeValueException(
							"Cannot set attribute " + name + " to null"));
				}
			}
			// if non null value, make sure it is assignable to the attribute
			else {
				if (java.lang.String.class.isAssignableFrom(value.getClass())) {
					setMessage((String) value);
				} else {
					throw (new InvalidAttributeValueException(
							"Cannot set attribute " + name + " to a "
									+ value.getClass().getName()
									+ " object, String expected"));
				}
			}
		} else if (name.equals("CountryCode")) {
			// if null value, try and see if the setter returns any exception
			if (value == null) {
				throw (new InvalidAttributeValueException(
						"Cannot set attribute " + name + " to null"));
			}
			// if non null value, make sure it is assignable to the attribute
			else {
				if (java.lang.Integer.class.isAssignableFrom(value.getClass())) {
					setCountryCode(((Integer) value).intValue());
				} else {
					throw (new InvalidAttributeValueException(
							"Cannot set attribute " + name + " to a "
									+ value.getClass().getName()
									+ " object, String expected"));
				}
			}
		}
		// unrecognized attribute name:
		else {*/
			throw (new AttributeNotFoundException("Attribute " + name
					+ " not found in " + this.getClass().getName()));
		/*}*/
	}

	/**
	 * Enables the to get the values of several attributes of the Dynamic MBean.
	 */
	public AttributeList getAttributes(String[] attributeNames) {

		// Check attributeNames is not null to avoid NullPointerException later
		// on
		if (attributeNames == null) {
			throw new RuntimeOperationsException(new IllegalArgumentException(
					"attributeNames[] cannot be null"),
					"Cannot invoke a getter of " + dClassName);
		}
		AttributeList resultList = new AttributeList();

		// if attributeNames is empty, return an empty result list
		if (attributeNames.length == 0)
			return resultList;

		// build the result attribute list
		for (int i = 0; i < attributeNames.length; i++) {
			try {
				Object value = getAttribute((String) attributeNames[i]);
				resultList.add(new Attribute(attributeNames[i], value));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return resultList;
	}

	/**
	 * Sets the values of several attributes of the Dynamic MBean, and returns
	 * the list of attributes that have been set.
	 */
	public AttributeList setAttributes(AttributeList attributes) {

		// Check attributes is not null to avoid NullPointerException later on
		if (attributes == null) {
			throw new RuntimeOperationsException(new IllegalArgumentException(
					"AttributeList attributes cannot be null"),
					"Cannot invoke a setter of " + dClassName);
		}
		AttributeList resultList = new AttributeList();

		// if attributeNames is empty, nothing more to do
		if (attributes.isEmpty())
			return resultList;

		// for each attribute, try to set it and add to the result list if
		// successfull
		for (Iterator i = attributes.iterator(); i.hasNext();) {
			Attribute attr = (Attribute) i.next();
			try {
				setAttribute(attr);
				String name = attr.getName();
				Object value = getAttribute(name);
				resultList.add(new Attribute(name, value));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return resultList;
	}

	/**
	 * Allows an operation to be invoked on the Dynamic MBean.
	 */
	public Object invoke(String operationName, Object params[],
			String signature[]) throws MBeanException, ReflectionException {

		// Check operationName is not null to avoid NullPointerException later
		// on
		if (operationName == null) {
			throw new RuntimeOperationsException(new IllegalArgumentException(
					"Operation name cannot be null"),
					"Cannot invoke a null operation in " + dClassName);
		}
		// Check for a recognized operation name and call the corresponding
		// operation
		if (operationName.equals("queryNames")) {
			try {
				return queryNames((String)params[0],(String)params[1]);
			} catch (MBeanServerException e) {
                throw new MBeanException(e);
			}
		} else{
			// unrecognized operation name:
			throw new ReflectionException(new NoSuchMethodException(
					operationName), "Cannot find the operation "
					+ operationName + " in " + dClassName);
		}
	}


	private String dClassName = this.getClass().getName();

	private String dDescription = "Simple implementation of a dynamic config MBean.";

	private MBeanAttributeInfo[] dAttributes = new MBeanAttributeInfo[3];

	private MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[1];

	private MBeanOperationInfo[] dOperations = new MBeanOperationInfo[1];

	private MBeanInfo dMBeanInfo = null;

	/**
	 * This method provides the exposed attributes and operations of the Dynamic
	 * MBean. It provides this information using an MBeanInfo object.
	 */
	public MBeanInfo getMBeanInfo() {
		// return the information we want to expose for management:
		// the dMBeanInfo private field has been built at instanciation time,

		if (dMBeanInfo == null)
			buildDynamicMBeanInfo();
		return dMBeanInfo;
	}

	/**
	 * Build the private dMBeanInfo field, which represents the management
	 * interface exposed by the MBean; that is, the set of attributes,
	 * constructors, operations and notifications which are available for
	 * management.
	 * 
	 * A reference to the dMBeanInfo object is returned by the getMBeanInfo()
	 * method of the DynamicMBean interface. Note that, once constructed, an
	 * MBeanInfo object is immutable.
	 */
	private void buildDynamicMBeanInfo() {

		dAttributes[0] = new MBeanAttributeInfo("Message", "java.lang.String",
				"Message: message string.", true, true, false);
		dAttributes[1] = new MBeanAttributeInfo("CountryCode",
				"java.lang.Integer",
				"CountryCode: standard country code integer.", true, true,
				false);

		Constructor[] constructors = this.getClass().getConstructors();
		dConstructors[0] = new MBeanConstructorInfo(
				"DynamicConfig(): Constructs a SimpleDynamic object",
				constructors[0]);

		MBeanParameterInfo[] params = null;
		dOperations[0] = new MBeanOperationInfo("sayHello",
				"sayHello(): simple operation", params, "void",
				MBeanOperationInfo.ACTION);

		dMBeanInfo = new MBeanInfo(dClassName, dDescription, dAttributes,
				dConstructors, dOperations, new MBeanNotificationInfo[0]);
	}

	// MBeanRegistration
	private boolean isRegistered = false;

	private MBeanServer mbeanServer = null;

	private ObjectName objectName = null;

	public ObjectName preRegister(MBeanServer server, ObjectName name)
			throws Exception {
		if (mbeanServer != null)
			throw new IllegalStateException(server + " tries to register "
					+ this + " is already registered by " + this.mbeanServer
					+ " as " + this.objectName);
		isRegistered = true;
		this.objectName = name;
		this.mbeanServer = server;
		return name;
	}

	public void postRegister(Boolean registrationDone) {
		if (registrationDone) {
			System.out.println(this + " is registered by " + mbeanServer
					+ " as " + objectName);
		} else {
			isRegistered = false;
			this.objectName = null;
			this.mbeanServer = null;
		}
	}

	public void preDeregister() throws Exception {
		System.out.println(this + " is unregistered by " + mbeanServer
				+ " for " + objectName);
		this.objectName = null;
		this.mbeanServer = null;
	}

	public void postDeregister() {
	}

	public Any getAttribute(String objectName, String attributeName)
			throws MBeanServerException {
		// TODO Auto-generated method stub
		return null;
	}

	public Any invokeOperation(String objectName, String operationName,
			String[] params) throws MBeanServerException {
		// TODO Auto-generated method stub
		return null;
	}

	public void setAttribute(String objectName, String attributeName,
			String attributeValue) throws MBeanServerException {
		// TODO Auto-generated method stub
		
	}
}
